package com.neusoft.elmboot.controller;

import com.neusoft.elmboot.po.DeliveryAddress;
import com.neusoft.elmboot.service.DeliveryAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/addresses")
public class DeliveryAddressController {

    @Autowired
    private DeliveryAddressService deliveryAddressService;

    @GetMapping("/list")
    public List<DeliveryAddress> listDeliveryAddressByUserId(@RequestParam String userId) throws Exception {
        return deliveryAddressService.listDeliveryAddressByUserId(userId);
    }

    @GetMapping("/{daId}")
    public DeliveryAddress getDeliveryAddressById(@PathVariable Integer daId) throws Exception {
        return deliveryAddressService.getDeliveryAddressById(daId);
    }

    @PostMapping
    public ResponseEntity<?> saveDeliveryAddress(@RequestBody DeliveryAddress deliveryAddress) {
        if (deliveryAddress.getUserId() == null || deliveryAddress.getContactName() == null) {
            return ResponseEntity.badRequest().body("userId、contactName 不能为空");
        }
        int rows = deliveryAddressService.saveDeliveryAddress(deliveryAddress);
        return rows > 0 ? ResponseEntity.ok(rows)
                        : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("插入失败");
    }

    @PutMapping
    public int updateDeliveryAddress(@RequestBody DeliveryAddress deliveryAddress) throws Exception {
        return deliveryAddressService.updateDeliveryAddress(deliveryAddress);
    }

    @DeleteMapping("/{daId}")
    public int removeDeliveryAddress(@PathVariable Integer daId) throws Exception {
        return deliveryAddressService.removeDeliveryAddress(daId);
    }
}